import java.util.Arrays;


public class Leetcode1984 {
    static {
        System.gc();
        System.runFinalization();
    }

    public static void main(String[] args) {
        System.out.println(minimumDifference(new int[]{9, 4, 1, 7}, 3));
    }

    public static int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);

        int n = nums.length;
        int min = Integer.MAX_VALUE;

        for (int i = 0; i < n - k + 1; i++) {
            min = Math.min(min, nums[i + k - 1] - nums[i]);
        }

        return min;
    }

}
